package com.raysdata.smartcity.web.sys;

import com.alibaba.fastjson.JSON;
import com.raysdata.smartcity.HelperClazz;
import com.raysdata.smartcity.Key;
import com.raysdata.smartcity.dao.sys.OrgDao;
import com.raysdata.smartcity.dto.Organization;
import com.raysdata.smartcity.dto.User;
import com.raysdata.smartcity.web.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * Created by bh on 2016/11/21.
 * 组织controller
 */
@Controller
@RequestMapping(value = "/org")
public class OrgController extends BaseController {

    @Autowired
    public OrgDao orgDao;

    @RequestMapping(value = "/toOrgIndex", method = RequestMethod.GET)
    public String toOrgIndex(Model model, HttpServletRequest request, HttpServletResponse response) {
//        StringBuilder tree = new StringBuilder();
//        tree.append("[");
//        try {
//            tree.append(this.getTreeChild(null));
//        }catch (Exception e){
//            e.printStackTrace();
//        }
//        tree.append("]");
//        request.setAttribute("orgData",tree.toString());
        return "smartcity/orgManage/orgList";
    }
    @RequestMapping(value = "/toOrgAdd")
    public String toOrgAdd(Model modele,HttpServletRequest request){
        return "smartcity/orgManage/orgAdd";
    }
    @RequestMapping(value = "/toOrgUpdate")
    public String toOrgUpdate(Model modele,HttpServletRequest request){
        request.setAttribute("org",orgDao.getOrgById(request.getParameter("org_id")));
        return "smartcity/orgManage/orgUpdate";
    }
    @RequestMapping(value = "/save")
    public void save(@ModelAttribute("Organization")Organization org,HttpServletRequest request, HttpServletResponse response){
        String type="";
        String content="";
        User user=(User)request.getSession().getAttribute("LoginUser");

        int result=-1;
        if(org.getIs_dept()==null || org.getIs_dept().equals("")){
            org.setIs_dept("0");
        }

        if(HelperClazz.isEmpty(org.getOrg_id())){
            User u=(User)request.getSession().getAttribute("LoginUser");
            Organization parentOrg=orgDao.getOrgById(org.getParent_id());
            org.setOrg_id(UUID.randomUUID().toString().trim().replaceAll("-", ""));
            org.setCperson(u.getLogin_name());
            org.setStatus("0");
            org.setCdate(new Date());
            org.setOrg_code(parentOrg.getOrg_code()+org.getOrg_code()+"_");
            result=orgDao.insert(org);
            type= Key.LOG_ADD;
            content="新增组织机构："+org.getName();
        }else{
            result=orgDao.update(org);
            type=Key.LOG_UPDATE;
            content="修改组织机构："+org.getName();
        }
        if(result!=-1){
            logDao.saveLog(request,content,type,user,org.getOrg_id(),Key.LOG_SUCCESS);
            HelperClazz.renderJson(response, "{\"success\":true,\"msg\":\"组织机构保存成功！\"}");
        }else{
            logDao.saveLog(request,content,type,user,org.getOrg_id(),Key.LOG_ERROR);
            HelperClazz.renderJson(response, "{\"success\":false,\"msg\":\"组织机构保存失败！\"}");
        }
    }
    @RequestMapping(value = "/deleteOrg")
    public void deleteOrg(HttpServletRequest request, HttpServletResponse response){
        String org_id=request.getParameter("org_id");
        Organization org=orgDao.getOrgById(org_id);
        String content="删除组织机构：";
        String type=Key.LOG_DELETE;

        // 获取当前用户
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("LoginUser");
        if(userDao.getUserCountByOrgCode(org.getOrg_code())>0){
            HelperClazz.renderJson(response, "{\"success\":false,\"msg\":\"组织机构下存在在用用户，不可删除！\"}");
            return;
        }
        if(orgDao.delete(org)!=-1){
            logDao.saveLog(request,content+org.getName(),type,user,org.getOrg_id(), Key.LOG_SUCCESS);
            HelperClazz.renderJson(response, "{\"success\":true,\"msg\":\"组织机构删除成功！\"}");
        }else{
            logDao.saveLog(request,content+org.getName(),type,user,org.getOrg_id(), Key.LOG_ERROR);
            HelperClazz.renderJson(response, "{\"success\":false,\"msg\":\"组织机构删除失败！\"}");
        }
    }

    @RequestMapping(value = "/getOrgTree")
    public void getOrgTree(HttpServletRequest request, HttpServletResponse response){
        String parentId=request.getParameter("parentId");
        List orgList=new ArrayList();
        if(parentId.equals("") || parentId==null){
            Map map=new HashMap();
            Organization org=orgDao.getOrgListByParentNull();
            List<Organization> orgs=orgDao.getOrgListByParentId(org.getOrg_id());
            map.put("org_id",org.getOrg_id());
            map.put("name",org.getName());
            map.put("full_name",org.getFull_name());
            map.put("org_code",org.getOrg_code());
            map.put("sort_no",org.getSort_no());
            map.put("children",orgs);
            orgList.add(map);
        }else{
            orgList=orgDao.getOrgListByParentId(parentId);
        }
        HelperClazz.renderJson(response, JSON.toJSONString(orgList));

    }
    public String getTreeChild(String parentId){
        StringBuilder tree = new StringBuilder();
        List<Organization> orgList=new ArrayList<Organization>();
        if(parentId!=null && !parentId.equals("")){
            orgList=orgDao.getOrgListByParentId(parentId);
        }else{
            orgList.add(orgDao.getOrgListByParentNull());
        }
        for(int i=0;i<orgList.size();i++){
            if(i==0 && parentId!=null && !parentId.equals("")){
                tree.append(",\"children\":[");
            }
            tree.append("{ \"id\":\""+orgList.get(i).getOrg_id()+"\",");
            tree.append("\"name\":\""+orgList.get(i).getName()+"\",");
            tree.append("\"full_name\":\""+orgList.get(i).getFull_name()+"\",");
            tree.append("\"code\":\""+orgList.get(i).getOrg_code()+"\",");
            tree.append("\"sort_no\":\""+orgList.get(i).getSort_no()+"\"");
            tree.append(getTreeChild(orgList.get(i).getOrg_id()));
            if(i==orgList.size()-1){
                if(parentId!=null && !parentId.equals("")){
                    tree.append("}]");
                }else{
                    tree.append("}");
                }
            }else{
                tree.append("},");
            }
        }
        return tree.toString();
    }
    @RequestMapping(value = "/checkName")
    public void checkName(HttpServletRequest request, HttpServletResponse response){
        String name = request.getParameter("name");
        String parent_id = request.getParameter("parent_id");
        String org_id = request.getParameter("org_id");

        boolean bl;
        if(HelperClazz.isEmpty(org_id)){
            bl =  rzBaseDao.chkIsExist("ss_org", " parent_id='"+parent_id+"' and full_name", name)==0;
        }else{
            String nameDb=orgDao.getOrgById(org_id).getFull_name();
            if(nameDb.equals(name)){
                bl=true;
            }else{
                bl = rzBaseDao.chkIsExist("ss_org", " parent_id='"+parent_id+"' and full_name", name)==0;
            }
        }
        HelperClazz.renderJson(response, "{ \"valid\": " + bl + " }");
    }

    @RequestMapping(value = "/checkCode")
    public void checkCode(HttpServletRequest request, HttpServletResponse response){
        String org_code = request.getParameter("org_code");
        String org_id = request.getParameter("org_id");

        boolean bl;
        if(HelperClazz.isEmpty(org_id)){
            System.out.print(rzBaseDao.chkLikeIsExist("ss_org", "org_code", "_"+org_code+"_"));
            bl =  rzBaseDao.chkLikeIsExist("ss_org", "org_code", "\\_"+org_code+"\\_")==0;
        }else{
            String nameDb=orgDao.getOrgById(org_id).getOrg_code();
            if(nameDb.contains(org_code)){
                bl=true;
            }else{
                bl = rzBaseDao.chkLikeIsExist("ss_org", "org_code", "\\_"+org_code+"\\_")==0;
            }
        }
        HelperClazz.renderJson(response, "{ \"valid\": " + bl + " }");
    }

}
